
import cv2
import time,PIL,os
from PIL import ImageGrab
import numpy as np
import time
from tempfile import NamedTemporaryFile
#截图
class ScreenCut:
        print("0000000000000")
    def __init__(self):
        if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/"):
            os.makedirs("E:/ningyuan/sumimoto/Curelasto/tmp/")
        try:
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png")
            os.remove("tmp/cut.png")
        except:pass
        print("11111111111111111")
        self.scrImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png","wb+")
        self.cutImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png","wb+")
    def cut(self):
        self.scrren_cut()
        self.img = cv2.imread(self.scrImg.name)
        cv2.namedWindow('image', cv2.WND_PROP_FULLSCREEN)
        cv2.setWindowProperty('image', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
        cv2.setMouseCallback('image', self.on_mouse)
        cv2.imshow('image', self.img)
        cv2.waitKey(0)
    def scrren_cut(self):
        # img = ImageGrab.grab(bbox=(250, 161, 1141, 610))
        image = ImageGrab.grab()
        image.save(self.scrImg.name)
        # PIL image to OpenCV image
    def on_mouse(self,event, x, y, flags, param):
        self.img2 = self.img.copy()
        if event == cv2.EVENT_LBUTTONDOWN:         #左键点击
            self.point1 = (x,y)
            #cv2.circle(img2, point1, 10, (0,255,0), 5)
            cv2.imshow('image', self.img2)
        elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):            #按住左键拖曳
            height,width = self.img2.shape[:2]
            cv2.rectangle(self.img2, self.point1,(x,y),(255,0,0),2)

            cv2.imshow('image', self.img2)
        elif event == cv2.EVENT_LBUTTONUP:         #左键释放
            self.point2 = (x,y)
            cv2.rectangle(self.img2, self.point1, self.point2, (0,0,255), 5)
            cv2.imshow('image', self.img2)
            min_x = min(self.point1[0],self.point2[0])
            min_y = min(self.point1[1],self.point2[1])
            width = abs(self.point1[0] - self.point2[0])
            height = abs(self.point1[1] - self.point2[1])
            cut_img = self.img[min_y:min_y+height, min_x:min_x+width]
            cv2.imwrite(self.cutImg.name, cut_img)
            cv2.destroyWindow("image")
            self.scrImg.close()
            os.remove(self.scrImg.name)
            del self.scrImg